using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CatLib;
using System;
using Bingo.Game;
using UnityEngine.Audio;
using UnityScript.Steps;

public enum EAudioType
{
    ENone = 0,
    EBg_Main = 1,
    EBg_Game = 2,
    EBtnClick = 3, //按钮点击
    EBlockDes = 4, // 砖块销毁
    EShoot = 5,
    ETouchWall = 6, //墙壁碰撞
    EGameSuc = 7, //胜利
    EGameLose = 8, //失败
}

public class AudioController : MonoBehaviour
{
    public static AudioController Instance;
    [SerializeField] private int HitMin = 1, HitMax = 8, EffectAudioSourceMax = 5; //碰撞随机音效


    [Tooltip("结束时将背景音乐设置成0.3")] [SerializeField] [Range(0, 1)]
    private float FinshBgVolume = 0.3f;

    [Range(1, 10)] [SerializeField] private int BgVolumeUpSpeed = 1;

    [SerializeField] private AudioSource _ASBgMusic, _ASAudioSound;

    [SerializeField] private string HitPre = "hit";

    private const string Prefs_Key_Sound = "Prefs_Key_Sound"; //on:0 off:1
    private const string Prefs_Key_Music = "Prefs_Key_Music"; //on:0 off:1

    private List<AudioSource> _listASSoundEffect; //音效播放
    private int _SoundIndex = 0;


    public delegate void HandlerAudioComp();

    public bool _IsSoundOn
    {
        private set
        {
            PlayerPrefs.SetInt(Prefs_Key_Sound, value ? 0 : 1);
            if (value)
            {
                PlayAudio(EAudioType.EBtnClick);
            }
            else
            {
                StopSound();
            }
        }
        get
        {
            if (PlayerPrefs.HasKey(Prefs_Key_Sound))
            {
                return PlayerPrefs.GetInt(Prefs_Key_Sound) == 0;
            }

            return true;
        }
    }

    public bool _IsMusicOn
    {
        private set
        {
            PlayerPrefs.SetInt(Prefs_Key_Music, value ? 0 : 1);
            if (value)
            {
//                PlayBgByGameState(GameController.Instance.GameState);
            }
            else
            {
                StopBg();
            }
        }
        get
        {
            if (PlayerPrefs.HasKey(Prefs_Key_Music))
            {
                return PlayerPrefs.GetInt(Prefs_Key_Music) == 0;
            }

            return true;
        }
    }

    private Dictionary<string, AudioClip> _dicAudio;

    void Awake()
    {
        Instance = this;
        _dicAudio = new Dictionary<string, AudioClip>();
//        if (_ASAudioSound == null)
//            _ASAudioSound = this.gameObject.AddComponent<AudioSource>();
        if (_ASBgMusic == null)
            _ASBgMusic = this.gameObject.AddComponent<AudioSource>();
        _listASSoundEffect = new List<AudioSource>(EffectAudioSourceMax);
        for (int i = 0; i < EffectAudioSourceMax; i++)
        {
            AudioSource asou = this.gameObject.AddComponent<AudioSource>();
            _listASSoundEffect.Add(asou);
        }
    }

    public void Init()
    {
        // _IsMute=玩家偏好赋值
        if (!_IsMusicOn)
            return;
        PlayAudio(EAudioType.EBg_Main);
    }

/*    public void PlayBgByGameState(GameState gameState)
    {
        if (gameState == GameState.STOP)
        {
            AudioController.Instance.PlayAudio(EAudioType.EBg_Main);
        }
        else if (gameState == GameState.RUNNING)
        {
            AudioController.Instance.PlayAudio(EAudioType.EBg_Game);
        }
    }*/

    public void PlayAudio(EAudioType eAudioType)
    {
        switch (eAudioType)
        {
            case EAudioType.EBg_Game:
                PlayBgMusic(BAssetBundle.Audios.BG_GAME);
                break;
            case EAudioType.EBg_Main:
                PlayBgMusic(BAssetBundle.Audios.BG_MAIN);
                break;
            case EAudioType.EBtnClick:
            case EAudioType.EBlockDes:
                string name = HitPre + UnityEngine.Random.Range(HitMin, HitMax + 1);
                PlaySoundAudio(name);
                break;
            case EAudioType.EShoot:
                PlaySoundAudio(BAssetBundle.Audios.SHOOT);
                break;
            case EAudioType.ETouchWall:
                PlaySoundAudio(BAssetBundle.Audios.TOUCH);
                break;
            case EAudioType.EGameSuc:
                SetBgMusicVolume(FinshBgVolume);
                PlaySoundAudio(BAssetBundle.Audios.GAME_SUC, OnFinshSoundComplete);
                break;
            case EAudioType.EGameLose:
                SetBgMusicVolume(FinshBgVolume);
                PlaySoundAudio(BAssetBundle.Audios.GAME_LOSE, OnFinshSoundComplete);
                break;
        }
    }

    /// <summary>
    /// 音乐放完或者界面关闭
    /// </summary>
    public void OnFinshSoundComplete()
    {
        StopSound();
        StartCoroutine(ItorMusicVolumeToMax());
    }

    public void PlayBgMusic(string bgMusicName)
    {
        if (!_IsMusicOn)
            return;
        AudioClip clip = GetAudioClip(bgMusicName);
        if (clip == null)
            return;
        _ASBgMusic.clip = clip;
        _ASBgMusic.Play();
        _ASBgMusic.loop = true;
    }

    public void StopBg()
    {
        _ASBgMusic.Stop();
    }

    public void PlaySoundAudio(string audioName, HandlerAudioComp callback = null)
    {
        if (!_IsSoundOn)
            return;

        AudioClip clip = GetAudioClip(audioName);
        if (clip == null)
            return;

        _SoundIndex = _SoundIndex + 1 < EffectAudioSourceMax ? ++_SoundIndex : 0;

        AudioSource aus = _listASSoundEffect[_SoundIndex];
        aus.clip = clip;
        aus.Play();
        aus.loop = false;
        if (callback != null)
        {
            StartCoroutine(ItorListenerSoundCompl(clip.length, callback));
        }

//        _ASAudioSound.clip = clip;
//        _ASAudioSound.Play();
//        _ASAudioSound.loop = false;
    }


    public void StopSound()
    {
        for (int i = 0; i < _listASSoundEffect.Count; i++)
        {
            _listASSoundEffect[i].Stop();
        }
    }

    public void SetEffectVolume(float volume)
    {
        _listASSoundEffect[_SoundIndex].volume = volume;
    }

    public void SetBgMusicVolume(float volume)
    {
        _ASBgMusic.volume = volume;
    }

    public AudioClip GetAudioClip(string audioName)
    {
        if (!_dicAudio.ContainsKey(audioName))
        {
            AudioClip clip = Bingo.Facades.Resources.LoadSync<AudioClip>(BAssetBundle.Audios.BundleName, audioName);
            if (clip == null)
                return null;
            _dicAudio.Add(audioName, clip);
        }

        return _dicAudio[audioName];
    }

    public bool SwithMusicState()
    {
        _IsMusicOn = !_IsMusicOn;
        return _IsMusicOn;
    }

    public bool SwitchSoundState()
    {
        _IsSoundOn = !_IsSoundOn;
        return _IsSoundOn;
    }

    private IEnumerator ItorListenerSoundCompl(float time, HandlerAudioComp callBack)
    {
        yield return new WaitForSeconds(time);
        callBack.Invoke();
    }

    private IEnumerator ItorMusicVolumeToMax()
    {
        if (!_IsMusicOn)
        {
            yield break;
        }
        else
        {
            while (_ASBgMusic.volume < 1)
            {
                yield return new WaitForEndOfFrame();
                _ASBgMusic.volume += 0.01f * BgVolumeUpSpeed;
            }
        }
    }
}